package com.hx.vending.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hx.vending.bean.Equipment;
import com.hx.vending.bean.Field;
import com.hx.vending.bean.OnlineOrder;
import com.hx.vending.bean.OrderBuy;
import com.hx.vending.bean.*;
import com.hx.vending.bean.entity.*;
import com.hx.vending.dao.EquipmentMapper;
import com.hx.vending.dao.FieldMapper;
import com.hx.vending.dao.OnlineOrderMapper;
import com.hx.vending.dao.OrderBuyMapper;
import com.hx.vending.dao.*;
import com.hx.vending.service.IOnlineOrderService;
import com.hx.vending.util.BigDecimalUtils;
import com.hx.vending.util.DateUtil;
import com.hx.vending.util.Msg;
import com.hx.vending.util.ToolUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/12/7.
 */
@Service
public class OnlineOrderServiceImpl implements IOnlineOrderService {
    @Autowired
    private OnlineOrderMapper onlineOrderMapper;
    @Autowired
    private EquipmentMapper equipmentMapper;
    @Autowired
    private FieldMapper fieldMapper;
    @Autowired
    private OrderBuyMapper orderBuyMapper;
    @Autowired
    private GoodsConsumeMapper goodsConsumeMapper;
    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public Msg selectOnlineOrderUserId(Integer userId,String startTime,String endTime,Integer[] integers) {
        if(ToolUtil.isEmpty(userId)){
            return Msg.fail().add("msg","用户信息不能为空");
        }
        try {
            List<OnlineOrder> onlineOrderList = onlineOrderMapper.selectByUserId(userId,startTime,endTime,integers);
            //当日支付总人数
            int count = onlineOrderMapper.selectCountPeople(userId,startTime,endTime,integers);
            //当日线上总钱数
            Double Money = onlineOrderMapper.selectCountMoney(userId,startTime,endTime,integers);
            //Double moneyFile = orderBuyMapper.selectMoneyFile(userId,null ,startTime,endTime);
            Orderdata data = new Orderdata();
            //总笔数
            data.setTotalnumber(onlineOrderList.size());
            //总人数
            data.setPeople(count);
            //总钱数
            data.setTransactionMoney(Money);
            return Msg.success().add("data", data);
        }catch (Exception e){
            Orderdata data = new Orderdata();
            //总笔数
            data.setTotalnumber(0);
            //总人数
            data.setPeople(0);
            data.setTransactionMoney(0D);
            return Msg.success().add("data", data);
        }
    }

    @Override
    public Msg getOnlineOrderList(Map<String, Object> paramMap,Integer userId,Integer[] integers) {
        Msg returnMsg = Msg.success();
        if (ToolUtil.isEmpty(paramMap.get("pageNum")) || (Integer) paramMap.get("pageNum") <= 0) {
            return Msg.fail().add("msg", "错误的页数值");
        }
        if (ToolUtil.isEmpty(userId)) {
            return Msg.fail().add("msg", "用户信息不能为空");
        }
        if(ToolUtil.isNotEmpty(paramMap.get("onlineOrderState"))){
            if(paramMap.get("onlineOrderState").equals(3)){
                paramMap.put("onlineOrderState",null);
            }
        }
        //分页页数 从pageNum开始，查十条
        Integer pageNum = ((Integer) paramMap.get("pageNum") - 1) * 10;
        //添加到map中
        paramMap.put("pageNum", pageNum);
        paramMap.put("userId",userId);
        paramMap.put("integers",integers);
        //查询数据
        List<OnlineOrderVo> list = onlineOrderMapper.getOnlineOrderVoList(paramMap);
        for(OnlineOrderVo onlineOrderVO:list){
            // 余币
            if (onlineOrderVO.getOnlineOrderMoney() == null) {
                onlineOrderVO.setOnlineOrderMoney(0D);
            }
        }
        //添加集合到返回Msg中
        returnMsg.add("resultList", list);
        return returnMsg;
    }

    @Override
    public Msg getOrderList(Map<String, Object> paramMap, Integer userId, Integer[] integers) {
        Msg returnMsg = Msg.success();
        if (ToolUtil.isEmpty(paramMap.get("pageNum")) || (Integer) paramMap.get("pageNum") <= 0) {
            return Msg.fail().add("msg", "错误的页数值");
        }
        if (ToolUtil.isEmpty(userId)) {
            return Msg.fail().add("msg", "用户信息不能为空");
        }
        if(ToolUtil.isNotEmpty(paramMap.get("onlineOrderState"))){
            if(paramMap.get("onlineOrderState").equals(3)){
                paramMap.put("onlineOrderState",null);
            }
        }
        //分页页数 从pageNum开始，查十条
        Integer pageNum = ((Integer) paramMap.get("pageNum") - 1) * 10;
        //添加到map中
        paramMap.put("pageNum", pageNum);
        paramMap.put("userId",userId);
        paramMap.put("integers",integers);
        //查询数据
        List<OnlineOrderVo> list = onlineOrderMapper.getOnlineOrderList(paramMap);
        //添加集合到返回Msg中
        returnMsg.add("resultList", list);
        return returnMsg;
    }


    /**
     * 微信支付添加订单信息
     * @param outTradeNoStr    商户订单号
     * @param equipmentId      设备id
     * @param total            金额
     * @return
     */
    public Integer insertOnlineOrder(String outTradeNoStr, String equipmentId, Double total){

        if (ToolUtil.isNotEmpty(outTradeNoStr) && ToolUtil.isNotEmpty(equipmentId)) {
            OnlineOrder onlineOrder = new OnlineOrder();
            //商户订单号
            onlineOrder.setOnlineOrderMerchantNumber(outTradeNoStr);
            //金额
            onlineOrder.setOnlineOrderMoney(total);
            //时间
            onlineOrder.setOnlineOrderTime(DateUtil.getTime());
            //状态 0未支付，1支付成功  2支付失败
            onlineOrder.setOnlineOrderState(0);
            //类型 1微信    2支付宝
            onlineOrder.setOnlineOrderType("1");
            //设备id
            onlineOrder.setOnlineOrderEquipmentId(equipmentId);
            //是否出货(0.未出货  1.已出货  2.出货失败)
            onlineOrder.setOnlineOrderShipment(0);

            //查询商户id
            Equipment equipment = new Equipment();
            equipment.setEquipmentId(equipmentId);
            Equipment selectEquipment = this.equipmentMapper.selectByPrimary(equipment);

            //用户id
            onlineOrder.setOnlineOrderUserId(selectEquipment.getEquipmentUserId());
            //场地id
            onlineOrder.setOnlineOrderFileldId(selectEquipment.getEquipmentFieldId());

            //保存订单信息
            int result = this.onlineOrderMapper.insertSelective(onlineOrder);

            OnlineOrder selectOnlineOrder = this.onlineOrderMapper.selectByPrimaryKeySelective(onlineOrder);
            if (result != 0) {
                return selectOnlineOrder.getOnlineOrderId();
            }else {
                return 0;
            }
        }else {
            return 0;
        }
    }

    @Override
    public List<Map<String, Object>> selectOnlineOrderAmountByFieldId(List<Integer> fieldList, String startTime, String endTime, Integer userId) {
        return onlineOrderMapper.selectOnlineOrderAmountByFieldId(fieldList,startTime,endTime,userId);
    }

    /**
     * 根据id查询 Equipment
     *
     * @param
     * @return
     */
    public Equipment selectByEquipmentId(String EquipmentId) {
        Equipment equipment = new Equipment();
        equipment.setEquipmentId(EquipmentId);
        Equipment equi = equipmentMapper.selectByPrimary(equipment);
        return equi;
    }

    /**
     * 根据id查询 Field
     *
     * @param FieldId
     * @return
     */
    public Field selectByFieldId(Integer FieldId) {
        Field field = new Field();
        field.setFieldId(FieldId);
        Field fifi = fieldMapper.selectByPrimary(field);
        return fifi;

    }


    /**
     * 线上榜单排行
     * @param startTime   开始时间
     * @param endTime     结束时间
     * @param pageNum     页码
     * @return
     */
    public Msg selectListRanking(String startTime, String endTime, Integer pageNum, Integer rankingNumber) {

        PageHelper.startPage(pageNum, rankingNumber);//1,10

        List<OnlineOrderRanking> onlineOrderRankingList = this.onlineOrderMapper.selectOnlineOrderRanking(startTime, endTime);

        PageInfo page = new PageInfo(onlineOrderRankingList, 5);
        return Msg.success().add("pageInfo", page).add("rankingList",onlineOrderRankingList);
    }



    /**
     * 根据线上订单id查询信息
     * @param onlineOrderId
     * @return
     */
    public Msg selectOnlineOrderById(Integer onlineOrderId) {

        if (ToolUtil.isNotEmpty(onlineOrderId)) {

            OnlineOrder onlineOrder = new OnlineOrder();
            onlineOrder.setOnlineOrderId(onlineOrderId);
            OnlineOrder selectOnlineOrder = this.onlineOrderMapper.selectByPrimaryKeySelective(onlineOrder);

            if (ToolUtil.isNotEmpty(selectOnlineOrder)) {

                if (selectOnlineOrder.getOnlineOrderState() == 2) {
                    return Msg.addCode(300);//订单失效
                }

                OrderBuy orderBuy = new OrderBuy();
                orderBuy.setOrderBuyParentId(onlineOrderId);
                List<OrderBuy> orderBuys = this.orderBuyMapper.selectByExampleSelective(orderBuy);

                for (OrderBuy forOrderBuy:orderBuys) {

                    //查询商品信息
                    Goods goods = new Goods();
                    goods.setGoodsId(forOrderBuy.getOrderBuyGoodsId());
                    Goods selectGoods = this.goodsMapper.selectByPrimaryKeySelective(goods);
                    if (ToolUtil.isNotEmpty(selectGoods)) {
                        forOrderBuy.setGoodsRemark(selectGoods.getGoodsRemark());
                    }
                }

                Equipment equipment = new Equipment();
                equipment.setEquipmentId(selectOnlineOrder.getOnlineOrderEquipmentId());
                Equipment selectEquipment = this.equipmentMapper.selectByPrimary(equipment);

                Field field = new Field();
                field.setFieldId(selectEquipment.getEquipmentFieldId());
                Field selectField = this.fieldMapper.selectByPrimary(field);

                return Msg.success().add("onlineOrder", selectOnlineOrder).add("orderGoods", orderBuys)
                        .add("equipmentNumber", selectEquipment.getEquipmentNumber()).add("fieldRegion", selectField.getFieldRegion())
                        .add("fieldAddress", selectField.getFieldAddress()).add("equipmentId", selectEquipment.getEquipmentId());
            }else {
                return Msg.fail().add("msg", "该订单不存在!!");
            }
        }else {
            return Msg.fail().add("msg", "传值为空");
        }
    }



    @Override
    public Msg getOnlineOrderByMerchantNumber(String merchantNumber) {
        OnlineOrder oo = new OnlineOrder();
        oo.setOnlineOrderMerchantNumber(merchantNumber);
        OnlineOrder onlineOrder = onlineOrderMapper.selectByPrimaryKeySelective(oo);
        if(ToolUtil.isNotEmpty(onlineOrder)){
            return Msg.success().add("onlineOrder",onlineOrder);
        }else{
            return Msg.fail().add("onlineOrder","没有此订单记录");
        }
    }

    @Override
    public OnlineOrder selectByPrimaryKeySelective(OnlineOrder onlineOrder) {
        return onlineOrderMapper.selectByPrimaryKeySelective(onlineOrder);
    }

    @Override
    public Msg selectOrderByEquipment(String equipmentId, Integer pageNum,Integer pageSize) {
        List<GoodsOrderVO> onlineOrderList = onlineOrderMapper.selectOrderByEquipment(equipmentId,pageNum,pageSize);
        for(int p = 0;p < onlineOrderList.size();p++){
            GoodsConsume goodsConsume = new GoodsConsume();
            goodsConsume.setGoodsOrderId(onlineOrderList.get(p).getOnlineOrderId());
            //商品
            List<GoodsDetailsVO> goodsDetailList = new ArrayList<>();
            //商品消耗表
            List<GoodsConsume> goodsConsumes = goodsConsumeMapper.selectByExample(goodsConsume);
            for(int i = 0;i < goodsConsumes.size();i++){
                if(goodsDetailList.size() > 0){
                    for(int j = 0;j < goodsDetailList.size();j++){
                        if(goodsConsumes.get(i).getGoodsConsumeGoodsId().equals(goodsDetailList.get(j).getGoodsId())){
                            goodsDetailList.get(j).setGoodsNumber(goodsDetailList.get(j).getGoodsNumber() + 1);
                        }else{
                            int x = 1;
                            int y = 1;
                            for(int k = 0;k < goodsDetailList.size();k++){
                                Goods go = new Goods();
                                go.setGoodsId(goodsConsumes.get(i).getGoodsConsumeGoodsId());
                                Goods goods = goodsMapper.selectByPrimaryKeySelective(go);
                                if(goodsDetailList.get(k).getGoodsId().equals(goods.getGoodsId())){
                                    y += 1;
                                    break;
                                }else{
                                    x += 1;
                                }
                            }
                            if(x > 1 && y <= 1){
                                GoodsDetailsVO goodsDetailsVO = new GoodsDetailsVO();
                                Goods go = new Goods();
                                go.setGoodsId(goodsConsumes.get(i).getGoodsConsumeGoodsId());
                                Goods goods = goodsMapper.selectByPrimaryKeySelective(go);
                                goodsDetailsVO.setGoodsId(goods.getGoodsId());
                                goodsDetailsVO.setGoodsName(goods.getGoodsName());
                                goodsDetailsVO.setGoodsPicture(goods.getGoodsPicture());
                                goodsDetailsVO.setGoodsPrice(goodsConsumes.get(i).getGoodsConsumePrice());
                                goodsDetailsVO.setGoodsNumber(1);
                                goodsDetailList.add(goodsDetailsVO);
                                break;
                            }
                        }
                    }
                }else{
                    GoodsDetailsVO goodsDetailsVO = new GoodsDetailsVO();
                    Goods go = new Goods();
                    go.setGoodsId(goodsConsumes.get(i).getGoodsConsumeGoodsId());
                    Goods goods = goodsMapper.selectByPrimaryKeySelective(go);
                    goodsDetailsVO.setGoodsId(goods.getGoodsId());
                    goodsDetailsVO.setGoodsName(goods.getGoodsName());
                    goodsDetailsVO.setGoodsPicture(goods.getGoodsPicture());
                    goodsDetailsVO.setGoodsPrice(goodsConsumes.get(i).getGoodsConsumePrice());
                    goodsDetailsVO.setGoodsNumber(1);
                    goodsDetailList.add(goodsDetailsVO);
                }

            }
            onlineOrderList.get(p).setList(goodsDetailList);
        }
        return Msg.success().add("goodsOrderList",onlineOrderList);
    }

}
